<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">

      <el-form-item label="项目标段" prop="institutionCode">
        <el-select
          v-model="queryParams.institutionCode"
          placeholder="请选择"
          size="small"
          style="width: 240px" @change="handleBidChange"
        >
          <el-option-group
            v-for="group in bidOptions"
            :key="group.name"
            :label="group.name">
            <el-option
              v-for="item in group.bids"
              :key="item.code"
              :label="item.name"
              :value="item.code">
            </el-option>
          </el-option-group>
        </el-select>
      </el-form-item>

      <el-form-item label="清单编码" prop="boqCode">
        <el-input
          v-model="queryParams.boqCode"
          placeholder="请输入清单编码"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="清单名称" prop="boqName">
        <el-input
          v-model="queryParams.boqName"
          placeholder="请输入清单名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="清单内码" prop="ancestors">
        <el-input
          v-model="queryParams.ancestors"
          placeholder="请输入清单内码"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['project:boq:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['project:boq:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['project:boq:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          @click="handleClean"
          v-hasPermi="['project:boq:remove']"
        >清空</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-upload2"
          size="mini"
          @click="handleImport"
          v-hasPermi="['project:boq:import']"
        >导入</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-share"
          size="mini"
          @click="handleMeterage"
          v-hasPermi="['project:boq:list']"
        >计量清单</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-check"
          size="mini"
          @click="handleSummary"
          v-hasPermi="['project:boq:summary']"
        >统计</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="boqList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="清单编码" align="left" prop="boqCode" width="100" />
      <el-table-column label="清单名称" align="left" prop="boqName" width="200" show-overflow-tooltip />
      <el-table-column label="上级清单" align="left" prop="parentCode" width="100" />
      <el-table-column label="单位" align="center" prop="unit" />
      <el-table-column label="单价" align="center" prop="price" />
      <el-table-column label="数量" align="center" prop="amount" />
      <el-table-column label="金额" align="center" prop="total" />
      <el-table-column label="复核数量" align="center" prop="reviewAmount" />
      <el-table-column label="复核金额" align="center" prop="reviewTotal" />
      <el-table-column label="变更数量" align="center" prop="changeAmount" />
      <el-table-column label="变更金额" align="center" prop="changeTotal" />
      <el-table-column label="显示顺序" align="center" prop="orderNum" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-share"
            v-if="scope.row.leafNode == 'Y'"
            @click="handleDetail(scope.row)"
          >计量清单</el-button>
        </template>
      </el-table-column>
      <el-table-column label="小数位" align="center" prop="decimalPlace" />
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改标段清单对话框 -->
    <el-dialog :title="title" :visible.sync="open" :close-on-click-modal="false" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">

        <el-form-item label="清单编码" prop="boqCode">
          <el-input v-model="form.boqCode" placeholder="请输入清单编码" :readonly="form.id != null" />
        </el-form-item>
        <el-form-item label="清单名称" prop="boqName">
          <el-input v-model="form.boqName" placeholder="请输入清单名称" />
        </el-form-item>
        <el-form-item label="上级清单" prop="parentCode">
          <treeselect v-model="form.parentCode" :options="treeOptions" :normalizer="normalizer" placeholder="选择上级清单" noOptionsText="暂无数据" noResultsText="未搜索到匹配项" />
        </el-form-item>
        <el-form-item label="单　　位" prop="unit">
          <el-input v-model="form.unit" placeholder="请输入单位" />
        </el-form-item>
        <el-form-item label="单　　价" prop="price">
          <el-input v-model="form.price" type="number" @input="calTotal" @keydown.native="handleKey" placeholder="请输入单价" />
        </el-form-item>
        <el-form-item label="数　　量" prop="amount">
          <el-input v-model="form.amount" type="number" @input="calTotal" @keydown.native="handleKey" placeholder="请输入数量" />
        </el-form-item>
        <el-form-item label="金　　额" prop="total">
          <el-input v-model="form.total" type="number" @keydown.native="handleKey" placeholder="请输入金额" />
        </el-form-item>
        <el-form-item label="显示顺序" prop="orderNum">
          <el-input v-model="form.orderNum" type="number" @keydown.native="handleKey" placeholder="请输入顺序" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 清单导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?institutionCode=' + this.queryParams.institutionCode"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
<!--          <div class="el-upload__tip" slot="tip">-->
<!--            <el-checkbox v-model="upload.updateSupport" /> 是否更新已经存在的清单数据-->
<!--          </div>-->
          <span>仅允许导入xls、xlsx格式文件。</span>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 计量清单对话框 -->
    <el-dialog :title="meterage.title" :visible.sync="meterage.open" width="75%" append-to-body>

      <el-form :model="meterage.queryParams" ref="meterageQueryForm" :inline="true" v-show="showSearch" label-width="68px">

<!--        <el-form-item label="起始桩号" prop="beginStation">-->
<!--          <el-input-->
<!--            v-model="meterage.queryParams.beginStation"-->
<!--            placeholder="请输入起始桩号"-->
<!--            clearable-->
<!--            size="small"-->
<!--            @keyup.enter.native="handleQuery"-->
<!--          />-->
<!--        </el-form-item>-->

<!--        <el-form-item label="截止桩号" prop="endStation">-->
<!--          <el-input-->
<!--            v-model="meterage.queryParams.endStation"-->
<!--            placeholder="请输入截止桩号"-->
<!--            clearable-->
<!--            size="small"-->
<!--            @keyup.enter.native="handleQuery"-->
<!--          />-->
<!--        </el-form-item>-->

        <el-form-item label="清单类型" prop="meterageBoqType">
          <el-select
            v-model="meterage.queryParams.meterageBoqType"
            placeholder="请选择"
            size="small"
            style="width: 240px"
          >
            <el-option
              v-for="item in meterage.meterageBoqTypeOptions"
              :key="item.value"
              :value="item.value"
              :label="item.label"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handelMeterageQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetMeterageQuery">重置</el-button>
        </el-form-item>

      </el-form>

      <el-table v-loading="meterage.loading" :data="meterage.meterageList">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="清单编号" align="left" prop="boqCode" width="100" />
        <el-table-column label="清单名称" align="left" prop="boqName" width="200" show-overflow-tooltip />
        <el-table-column label="单位" align="center" prop="unit" />
        <el-table-column label="起始桩号" align="center" prop="beginStation" />
        <el-table-column label="截止桩号" align="center" prop="endStation" />
        <el-table-column label="是否完成" align="center" prop="complete" >
          <template slot-scope="scope">
            <dict-tag :options="dict.type.sys_yes_no" :value="scope.row.complete"/>
          </template>
        </el-table-column>
        <el-table-column label="数量" align="center" prop="amount" />
        <el-table-column label="已计量数量" align="center" prop="alreadyAmount" />
        <el-table-column label="剩余数量" align="center" prop="remainderAmount" />
        <el-table-column label="金额" align="center" prop="total" />
        <el-table-column label="已计量金额" align="center" prop="alreadyTotal" />
        <el-table-column label="剩余金额" align="center" prop="remainderTotal" />
        <el-table-column label="清单类型" align="center" prop="meterageBoqType" >
          <template slot-scope="scope">
            <el-tag size="mini" v-if="scope.row.meterageBoqType == '0'">合同</el-tag>
            <el-tag size="mini" type="danger" v-if="scope.row.meterageBoqType == '1'">变更</el-tag>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-show="meterage.total>0"
        :total="meterage.total"
        :page.sync="meterage.queryParams.pageNum"
        :limit.sync="meterage.queryParams.pageSize"
        @pagination="getMeterageList"
      />
    </el-dialog>

  </div>
</template>

<script>
import { listBoq, getBoq, delBoq, addBoq, updateBoq, getTreeList, getTreeListExcludeChild,summary, clean } from "@/api/project/boq";
import {listMeterage} from "@/api/project/meterage";
import {selectProjectBidOrBranch} from "@/api/project/bid";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import {getToken} from "@/utils/auth";
import * as math from "mathjs";

export default {
  name: "Boq",
  dicts: ['sys_yes_no'],
  components: { Treeselect },
  data() {
    return {
      // 标段下拉框
      bidOptions: [],
      // 遮罩层
      loading: false,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 标段清单表格数据
      boqList: [],
      // 清单树选项
      treeOptions: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        institutionCode: null,
        boqCode: null,
        boqName: null,
        ancestors: null
      },
      // 计量清单参数
      meterage: {
        // 遮罩层
        loading: false,
        // 总条数
        total: 0,
        // 标题
        title: '',
        open: false,
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          institutionCode: null,
          institutionBoqCode: null,
          meterageBoqType: null,
          beginStation: null,
          endStation: null
        },
        // 计量清单表格数据
        meterageList: [],
        // 清单类型
        meterageBoqTypeOptions: [{
          value: '0',
          label: '合同'
        }, {
          value: '1',
          label: '变更'
        }],
      },
      // 清单导入参数
      upload: {
        // 是否显示弹出层（清单导入）
        open: false,
        // 弹出层标题（清单导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的清单数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { token: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/project/boq/importData"
      },
      // 表单参数
      form: {

      },
      // 表单校验
      rules: {
        boqCode: [
          { pattern: /(^[1-9][0-9]+)|(^[1-9][0-9]*(-\w+)+)/, message: "清单编码格式不正确", trigger: "blur" },
          { required: true, message: "清单编码不能为空", trigger: "blur" }
        ],
        boqName: [
          { required: true, message: "清单名称不能为空", trigger: "blur" }
        ],
        orderNum: [
          { required: true, message: "显示顺序不能为空", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    this.initBidSelect();
  },
  methods: {
    /** 初始化标段下拉框 */
    initBidSelect() {
      selectProjectBidOrBranch().then(response => {
        this.bidOptions = response.data;
        if (this.bidOptions.length > 0) {
          this.queryParams.institutionCode = this.bidOptions[0].bids[0].code;
          this.getList();
        }
      });
    },
    /** 查询标段清单列表 */
    getList() {
      this.loading = true;
      listBoq(this.queryParams).then(response => {
        this.boqList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 转换清单数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.boqCode,
        label: node.boqName,
        children: node.children
      };
    },
    /** 查询菜单下拉树结构 */
    getTreeSelect() {
      getTreeList({institutionCode: this.queryParams.institutionCode}).then(response => {
        this.treeOptions = this.handleTree(response.data, "boqCode", "parentCode");
      });
    },
    getTreeSelectExcludeChild(row) {
      const id = row.id || this.ids[0];
      getTreeListExcludeChild({institutionCode: this.queryParams.institutionCode, id: id}).then(response => {
        this.treeOptions = this.handleTree(response.data, "boqCode", "parentCode");
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        boqCode: null,
        boqName: null,
        parentCode: null,
        orderNum: undefined,
        unit: null,
        price: undefined,
        amount: undefined,
        total: undefined
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    handelMeterageQuery() {
      this.meterage.queryParams.pageNum = 1;
      this.getMeterageList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      if (this.bidOptions.length > 0) {
        this.queryParams.institutionCode = this.bidOptions[0].bids[0].code;
      }
      this.handleQuery();
    },
    resetMeterageQuery() {
      this.meterage.queryParams.beginStation = null;
      this.meterage.queryParams.endStation = null;
      this.meterage.queryParams.meterageBoqType = null;
      this.handelMeterageQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    // 标段下拉框发生变化
    handleBidChange() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 新增按钮操作 */
    handleAdd() {
      if (this.queryParams.institutionCode == null) {
        this.$modal.msgError("请选择项目标段");
        return;
      }
      this.reset();
      this.getTreeSelect();
      this.open = true;
      this.title = "添加标段清单";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      if (this.queryParams.institutionCode == null) {
        this.$modal.msgError("请先选择项目标段");
        return;
      }
      this.reset();
      const id = row.id || this.ids
      getBoq(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改标段清单";
        this.getTreeSelectExcludeChild(row);
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        this.form.institutionCode = this.queryParams.institutionCode;
        if (valid) {
          if (this.form.id != null) {
            updateBoq(this.form).then(response => {
              this.$modal.msgSuccess("操作成功");
              this.open = false;
              this.getList();
            });
          } else {
            addBoq(this.form).then(response => {
              this.$modal.msgSuccess("操作成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('确认删除选中的数据项？').then(function() {
        return delBoq(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("操作成功");
      }).catch(() => {});
    },
    /** 清空按钮操作 */
    handleClean() {
      if (this.queryParams.institutionCode == null) {
        this.$modal.msgError("请先选择项目标段");
        return;
      }
      this.$modal.confirm('确认清空该标段下所有工程量清单数据？').then(() => {
        return clean({ institutionCode: this.queryParams.institutionCode});
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("操作成功");
      }).catch(() => {});
    },
    /**
     * 汇总按钮操作
     */
    handleSummary() {
      if (this.queryParams.institutionCode == null) {
        this.$modal.msgError("请先选择项目标段");
        return;
      }
      summary({ institutionCode: this.queryParams.institutionCode}).then(response => {
        this.$modal.msgSuccess("操作成功");
        this.getList();
      });
    },
    /** 导入按钮操作 */
    handleImport() {
      if (this.queryParams.institutionCode == null) {
        this.$modal.msgError("请先选择项目标段");
        return;
      }
      this.upload.title = "标段清单导入";
      this.upload.open = true;
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert(response.msg, "导入结果", { dangerouslyUseHTMLString: true, customClass: "myMessageBox" });
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },
    handleKey(e) {
      let key = e.key
      // 不允许输入'e'和'.'
      if (key === 'e') {
        e.returnValue = false
        return false
      }
      return true
    },
    /**
     * 计量清单按钮操作
     */
    handleMeterage() {
      this.$router.push({ path: '/project/meterage/meterage', query: { institutionCode: this.queryParams.institutionCode } })
    },
    /**
     * 表格内计量清单按钮操作
     * @param row
     */
    handleDetail(row) {
      this.meterage.queryParams.pageNum = 1;
      this.meterage.queryParams.institutionCode = row.institutionCode;
      this.meterage.queryParams.institutionBoqCode = row.institutionBoqCode;
      this.meterage.title = row.boqCode;
      this.getMeterageList(row);
    },
    /** 查询计量清单列表 */
    getMeterageList() {
      this.meterage.loading = true;
      listMeterage(this.meterage.queryParams).then(response => {
        this.meterage.meterageList = response.rows;
        this.meterage.total = response.total;
        this.meterage.open = true;
        this.meterage.loading = false;

      });
    },
    calTotal() {
      this.form.total = math.round(this.form.amount * this.form.price, 6);
    }
  }
};
</script>

<style lang="scss">
  input::-webkit-outer-spin-button,
  input::-webkit-inner-spin-button {
    -webkit-appearance: none;
  }
  input[type='number'] {
    -moz-appearance: textfield;
  }
</style>
